package com.zktr.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String methodName = request.getParameter("method");
		String servlet = request.getServletPath();
		System.out.println("你调用的Servlet是"+servlet+"的"+methodName+"方法");
		Method method=null;
		try {
			method=this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
			method.setAccessible(true);
			String result=(String)method.invoke(this, request,response);
			if(result!=null && !result.trim().isEmpty()){
				String [] strings=result.split(":");
				if(strings[0].equals("f")){
					request.getRequestDispatcher(strings[1]).forward(request, response);
				}else if(strings[0].equals("r")){
					response.sendRedirect(request.getContextPath()+strings[1]);
				}
			}
		}catch (Exception e) {
			System.out.println("调用的方法不存在");
			e.printStackTrace();
		}
		
	}
}
